package com.begye.smartloan.apptest.jujue.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.begye.smartloan.apptest.R
import com.begye.smartloan.apptest.ext.isUrl
import com.begye.smartloan.apptest.ext.toThousandUnitFormat
import com.util.utillib.extend.openSystemBrowser
import org.json.JSONObject

class JuJueProductAdapter(var dataList: List<JSONObject>) :
    RecyclerView.Adapter<JuJueProductAdapter.ViewHolder>() {

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int,
    ): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.list_item_ju_jue_product, parent, false)
        return ViewHolder(view)
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        private val listItemJuJueProductLogo: ImageView =
            view.findViewById(R.id.listItemJuJueProductLogo)

        private val listItemJuJueProductName: TextView =
            view.findViewById(R.id.listItemJuJueProductName)

        private val listItemJuJueProductJinE: TextView =
            view.findViewById(R.id.listItemJuJueProductJinE)

        private val listItemJuJueProductRate: TextView =
            view.findViewById(R.id.listItemJuJueProductRate)

        private val listItemJuJueProductCount: TextView =
            view.findViewById(R.id.listItemJuJueProductCount)

        private val listItemJuJueProductAnZhuan: LinearLayout =
            view.findViewById(R.id.listItemJuJueProductAnZhuan)


        @SuppressLint("SetTextI18n")
        fun bindData(position: Int, item: JSONObject) {
            listItemJuJueProductName.text = item.optString("appName", "")

            val jinE = item.optString("appLoanAmount", "").toThousandUnitFormat()
            listItemJuJueProductJinE.text = jinE

            listItemJuJueProductRate.text = item.optString("star", "")
            listItemJuJueProductCount.text = item.optString("download", "")

            val link = item.optString("appLink", "")
            listItemJuJueProductAnZhuan.setOnClickListener {
                if (link.isUrl()) {
                    listItemJuJueProductAnZhuan.context.openSystemBrowser(link)
                }
            }

            val logo = item.optString("appLogo", "")
            if (logo.isUrl()) {
                Glide.with(listItemJuJueProductLogo.context)
                    .load(logo)
                    .into(listItemJuJueProductLogo)
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bindData(position, dataList[position])
    }

    override fun getItemCount(): Int {
        return dataList.size
    }
}